﻿namespace LeetCodeProject._0001_1000._101_200._101_110._107;

public class Solution
{
    public IList<IList<int>> LevelOrderBottom(TreeNode root)
    {
        return EnumNodes(root, 0).GroupBy(t => t.level)
            .Select(g => g.Select(t => t.node.val).ToList() as IList<int>).Reverse().ToList();
    }

    private IEnumerable<(TreeNode node, int level)> EnumNodes(TreeNode root, int level)
    {
        if (root == null)
        {
            yield break;
        }

        yield return (root, level);
        foreach (var node in EnumNodes(root.left, level + 1))
        {
            yield return node;
        }

        foreach (var node in EnumNodes(root.right, level + 1))
        {
            yield return node;
        }
    }
}